//1.创建一个map，存放剩下老节点 
const existingChildren = new Map();
let nodeA = {key:'A',mountIndex:0};
let nodeB = {key:'B',mountIndex:1};
let nodeC = {key:'C',mountIndex:2};
let nodeD = {key:'D',mountIndex:3};
let nodeE = {key:'E',mountIndex:4};
let nodeF = {key:'F',mountIndex:5};
//剩下的，等待被复用的老节点
existingChildren.set('B',nodeB);
existingChildren.set('C',nodeC);
existingChildren.set('D',nodeD);
existingChildren.set('E',nodeE);
existingChildren.set('F',nodeF);
//2.声明一个变量 上一个被放置好的不需要移动的老节点的的索引
let lastPlacedIndex = -1;
//3.开始遍历剩下的新节点
let newNodes = [
    {key:'C',mountIndex:1},
    {key:'E',mountIndex:2},
    {key:'B',mountIndex:3},
    {key:'G',mountIndex:4},
    {key:'D',mountIndex:5}
]
let patch = [];
//开始按顺序遍历剩下的新节点
for(let i=0;i<newNodes.length;i++){
    //得到当前循环的新节点
    let newNode = newNodes[i];
    //通过key去老节点的map中查找可以复用的,key相同的老节点
    let oldNode = existingChildren.get(newNode.key);
    //如果找到key相同的可以复用的老节点，就可以复用此老节点
    if(oldNode){
          //如果复用了，就可以把此老节点从existingChildren中删除
        existingChildren.delete(newNode.key);
       
        //让lastPlacedIndex等于复用的老节点的挂载索引
        //lastPlacedIndex=newNode.mountIndex;//lastPlacedIndex=2
        //如果可复用的老节点的索引小于上一个不需要移动的老节点索引的话，
        //那就需要移动老节点,此时不需要更新lastPlacedIndex
        if(oldNode.mountIndex<lastPlacedIndex){
            patch.push(`复用、更新并移动${newNode.key}，从${oldNode.mountIndex}到${newNode.mountIndex}`);
        }else{
            patch.push(`复用并更新${newNode.key}`);
            //如果找到可复用的老节点挂载索引比当前lastPlacedIndex要大，则它不需要移动，
            //但需要更新lastPlacedIndex为oldNode.mountIndex
            lastPlacedIndex=oldNode.mountIndex;
        }
    }else{
        //如果在map中找不到能复用的老节点，则创建新节点
        patch.push(`创建新的${newNode.key}`);
    }  
}
for(let key of existingChildren.keys()){
    patch.push(`删除 ${key}`);
}
console.log('patch',patch)
//最后会把留在existingChildren中的元素全部删除
